﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace rocket_console
{
    class Listen
    {
        public Socket client;
        public Socket newsock;
        public IPEndPoint clientip;
        public string msg;
        public int msgtimes=0;
        public void lis()
        {
            int recv;//用于表示客户端发送的信息长度
            byte[] data = new byte[1024];//用于缓存客户端所发送的信息,通过socket传递的信息必须为字节数组
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//本机预使用的IP和端口
            this.newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            this.newsock.Bind(ipep);//绑定
            this.newsock.Listen(10);//监听
            Console.WriteLine("waiting for a client");
            this.client = this.newsock.Accept();//当有可用的客户端连接尝试时执行，并返回一个新的socket,用于与客户端之间的通信
            this.clientip = (IPEndPoint)this.client.RemoteEndPoint;
            Console.WriteLine("connect with client:" + this.clientip.Address + " at port:" + this.clientip.Port);
            while (true)
            {//用死循环来不断的从客户端获取信息
                data = new byte[1024];
                recv = this.client.Receive(data);
                //Console.WriteLine("recv=" + recv);
                this.msg=Encoding.ASCII.GetString(data, 0, recv);
                if (this.msg!="")
                {
                    this.msgtimes++;
                    if (this.msgtimes==1)
                    {
                        Console.WriteLine("客户端握手请求信息");
                        Console.WriteLine(this.msg);//客户端握手请求信息
                        byte[] handshakemsg = Handshake.run(this.msg);
                        //Encoding.ASCII.GetBytes();;;;Encoding.UTF8.GetString();;;;
                        string servHandshake=Encoding.UTF8.GetString(handshakemsg, 0, handshakemsg.Length);
                        Console.WriteLine("服务器端握手信息");
                        Console.WriteLine(servHandshake);
                        this.client.Send(handshakemsg, handshakemsg.Length, SocketFlags.None);//发送信息
                        Console.WriteLine("握手完成，通讯开始\n\n");
                    }
                    else if (this.msgtimes>1)
                    {
                        string rcvMsg=Data.AnalyticData(data, recv);
                        Console.WriteLine(rcvMsg);
                    }
                }
            }
        }

        public void close()
        {
            Console.WriteLine("Disconnected from" + this.clientip.Address);//TODO
            this.client.Close();
            this.newsock.Close();
        }
        public static Listen run()
        {
            return new Listen();
        }
    }
}
